package com.alogic.loki.handler;

import com.alogic.loki.LokiStream;
import com.alogic.loki.util.LokiRelabel;
import com.anysoft.stream.Handler;
import com.anysoft.stream.SlideHandler;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.Settings;
import com.anysoft.util.XmlTools;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 对数据进行relabel
 *
 * @since 1.6.13.14 [20200907 duanyy] <br>
 */
public class Relabel extends SlideHandler<LokiStream> {
    /**
     * relabel规则
     */
    protected Collection<LokiRelabel> relables = new ArrayList<LokiRelabel>();
    @Override
    protected void onHandle(LokiStream t, long timestamp) {
        for (LokiRelabel relabel:relables){
            String key = relabel.getKey();
            LokiRelabel.Action action = relabel.getAction();
            if (action == LokiRelabel.Action.delete) {
                t.delLabel(key);
            } else {
                Properties props = t.getLabelProperties(false);
                if (props == null){
                    props = Settings.get();
                }
                String value = PropertiesConstants.transform(props, relabel.getValue(), "");
                if (relabel.isRefValue()){
                    value = PropertiesConstants.getString(props, value, "");
                }
                if (StringUtils.isNotEmpty(value)) {
                    t.setLabel(key, value, action == LokiRelabel.Action.overwrite);
                }
            }
        }
        Handler<LokiStream> handler = getSlidingHandler();
        if (handler != null){
            handler.handle(t, timestamp);
        }
    }

    @Override
    protected void onConfigure(Element e, Properties p) {
        super.onConfigure(e, p);
        NodeList nodeList = XmlTools.getNodeListByPath(e,"relabel");
        for (int i = 0 ; i< nodeList.getLength() ;i ++){
            Node node = nodeList.item(i);
            if (Node.ELEMENT_NODE != node.getNodeType()){
                continue;
            }
            Element n = (Element)node;

            String key = n.getAttribute("key");
            String value = n.getAttribute("value");
            String ref = n.getAttribute("ref");

            if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)){
                String action = n.getAttribute("action");
                relables.add(new LokiRelabel.Default(key,value, LokiRelabel.Action.valueOf(StringUtils.isEmpty(action)?"keep":action),Boolean.valueOf(ref)));
            }
        }
    }
}